package services

import (
	"encoding/json"
	"fmt"
	"github.com/parnurzeal/gorequest"
	common "jihe.common"
	"time"
)

type AlgorithmService struct {
	baseService
}

type AlgorithmConfig struct {
	Man      map[string]string `json:"man"`
	Woman    map[string]string `json:"woman"`
	Children map[string]string `json:"children"`
}

func (s *AlgorithmService) BaseGetAlgorithmConfig(tag string) (ret map[string]string, err error) {
	confData := AlgorithmConfig{}
	redisClient := s.Redis.Get()
	configDataB, _ := redisClient.Get(s.Redis.GetBaseAlgorithmConfigKey()).Bytes()
	if len(configDataB) != 0 {
		err = json.Unmarshal(configDataB, &confData)
		if err == nil {
			if tag == "men" {
				ret = confData.Man
			} else if tag == "women" {
				ret = confData.Woman
			} else if tag == "children" {
				ret = confData.Children
			}
			return
		}
	}
	configUrl := fmt.Sprintf("%s/%s_config.json?%d", common.Configer.Oss.Domain, common.Configer.Runmode, time.Now().UnixNano())
	_, body, errs := gorequest.New().Get(configUrl).Timeout(time.Second * 10).EndStruct(&confData)
	if len(errs) != 0 {
		err = errs[0]
		return
	}
	if tag == "men" {
		ret = confData.Man
	} else if tag == "women" {
		ret = confData.Woman
	} else if tag == "children" {
		ret = confData.Children
	}
	redisClient.Set(s.Redis.GetBaseAlgorithmConfigKey(), string(body), -1)
	return
}
